<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Cache;

class Config extends Base
{
    protected function getGroupAttr($value): string|array
    {
        return get_config_group($value);
    }

    protected function getTypeRowAttr($value, $data): string
    {
        return $data['type'];
    }

    public static function _saveGroup($param, $admin, $options): array
    {
        try {
            $msg = '';
            foreach ($param as $name => $value) {
                $info = parent::where('name', $name)->field('title,type,value,format,suffix')->find();
                if (empty($info)) continue;
                if ($info->getData('type') == 6) {
                    if ($info->value != $value) {
                        $msg .= '修改【' . $info->title . '】由<a target="_blank" href="' . $info['value'] . '">
                        <img style="width: 20px" src="' . $info['value'] . '"/></a>修改为<a target="_blank" href="' . $value . '">
                        <img style="width: 20px" src="' . $value . '"/></a>，';
                    }
                } else {
                    if ($info->value != $value) {
                        $msg .= "修改【{$info->title}】由【{$info['value']}】修改为【{$value}】，";
                    }
                }
                parent::update(['value' => $value], ['name' => $name]);
            }
            if ($msg) {
                Logs::adds($msg, $admin->id, $admin->admin_name);
            }
            Cache::delete('system');

            return ['code' => 1, 'msg' => '保存成功'];
        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function lists(): array
    {
        $list = parent::field('name,type,value')->where(['status' => 1])->select();
        $config = [];
        foreach ($list as $item) {
            $config[$item['name']] = self::parse($item['type'], $item['value']);
        }

        return $config;
    }

    private static function parse($type, $value): array|string
    {
        switch ($type) {
            case 3: //解析数组
                $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
                if (strpos($value, ':')) {
                    $value = [];
                    foreach ($array as $val) {
                        list($k, $v) = explode(':', $val);
                        $value[$k] = $v;
                    }
                } else {
                    $value = $array;
                }
                break;
        }

        return $value;
    }
}